package com.lishe.lishe.lishe.module.myorder.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.lishe.base.common.base.AbstractFragment;
import com.lishe.base.common.config.Constants;
import com.lishe.base.mvp.factory.CreatePresenter;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.AppManager;
import com.lishe.lishe.lishe.module.main.event.TabChangeEvent;
import com.lishe.lishe.lishe.module.myorder.activity.MyOrdersActivity;
import com.lishe.lishe.lishe.module.myorder.activity.OrderDetailActivity;
import com.lishe.lishe.lishe.module.myorder.adapter.OrderAdapter;
import com.lishe.lishe.lishe.module.myorder.bean.OrderListResponse;
import com.lishe.lishe.lishe.module.myorder.interfase.OrderButtonClickListener;
import com.lishe.lishe.lishe.module.myorder.presenter.OrderListContract;
import com.lishe.lishe.lishe.module.myorder.presenter.OrderListPresenter;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.net.BaseProtocal;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 标    题：
 * 功能描述：MyOrdersModelFragment OrderAdapter0
 * 作    者：zouxx
 * 创建时间：2018/8/21
 */

@CreatePresenter(OrderListPresenter.class)
public class OrdersFragment extends AbstractFragment<OrderListContract.OrderListView, OrderListPresenter> implements OrderListContract.OrderListView {

    private View rootView;
    private SmartRefreshLayout mRefreshlayout;
    private ExpandableListView mRecyclerView;
    //    private RecyclerView mRecyclerView;
    private LinearLayout mErrorLayout;
    private LinearLayout mEmptyLayout;

    private int page = 1, totalPage = 0;
    private int ORDER_TYPE = 0;
    private List<OrderListResponse.DataBean.ListBean> mOrderList = new ArrayList<>();
    //    private OrderListAdapter adapter;
    private OrderAdapter adapter;
    private boolean isInitData = false;

    public static OrdersFragment newInstance(int type) {
        OrdersFragment fragment = new OrdersFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
            ORDER_TYPE = getArguments().getInt("type");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_my_orders_model, null);
            initView(rootView);
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mOrderList == null) mOrderList = new ArrayList<>();
        if (mOrderList.size() == 0 && !isInitData) {
            page = 1;
            getMvpPresenter().getOrderList(page, String.valueOf(ORDER_TYPE));
            isInitData = true;
        }
    }

    private void initView(View rootView) {
        mRefreshlayout = rootView.findViewById(R.id.refreshlayout);
        mRecyclerView = rootView.findViewById(R.id.recyclerView);
        mErrorLayout = rootView.findViewById(R.id.error_layout);
        mEmptyLayout = rootView.findViewById(R.id.emptyLayout);
        adapter = new OrderAdapter(getActivity(), mOrderList);
        mRecyclerView.setGroupIndicator(null);
        mRecyclerView.setOnGroupClickListener((parent, v, groupPosition, id) -> {
            startOrderDetailActivity(groupPosition);
            return true;
        });
        adapter.setButtonListener(new OrderButtonClickListener() {
            @Override
            public void showConfirmDialog(String paymentId) {
                showSureConfirmDialog(paymentId);
            }

            @Override
            public void showCancelDialog(String paymentId) {
                showCancelOrderDialog(paymentId);
            }

            @Override
            public void updateUI(int groupPosition) {
                mOrderList.remove(groupPosition);
                adapter.notifyDataSetChanged();
                if (mOrderList.size() == 0) {
                    mRefreshlayout.setVisibility(View.GONE);
                    mEmptyLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        mRecyclerView.setOnChildClickListener((parent, v, groupPosition, childPosition, id) -> {
            startOrderDetailActivity(groupPosition);
            return false;
        });
        mRecyclerView.setOnItemClickListener((parent, view, position, id) -> {
            startOrderDetailActivity(position);
        });
        mRecyclerView.setAdapter(adapter);
        setListener();
    }

    private void startOrderDetailActivity(int position) {
        String tid = mOrderList.get(position).order_status == 1 || 2 == mOrderList.get(position).order_status || 3 == mOrderList.get(position).order_status
                || 4 == mOrderList.get(position).order_status ? "" : mOrderList.get(position).products.get(0).tid;
        Intent i = new Intent(context, OrderDetailActivity.class);
        i.putExtra(Constants.TID, tid);
        i.putExtra(Constants.PAYMENTID, mOrderList.get(position).payment_id);
        i.putExtra(Constants.ISREMINDSEND, mOrderList.get(position).isReminder);
        context.startActivity(i);
    }

    private void setListener() {
        rootView.findViewById(R.id.error_retry).setOnClickListener(v -> {
            page = 1;
            getMvpPresenter().getOrderList(page, String.valueOf(ORDER_TYPE));
        });
        rootView.findViewById(R.id.govisit).setOnClickListener(v -> {
            if (getActivity() != null && !getActivity().isFinishing()) {
                getActivity().finish();
            }
            EventBus.getDefault().post(new TabChangeEvent(0));
        });
        mRefreshlayout.setEnableLoadmore(true);
        mRefreshlayout.setOnRefreshListener(refreshlayout -> {
            // 更新显示的label
            reloadData();
            mRefreshlayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
            if (!mRefreshlayout.isEnableLoadmore()) refreshlayout.setEnableLoadmore(true);
        });
        mRefreshlayout.setOnLoadmoreListener(refreshlayout -> {
            if (page <= totalPage) {
                mRefreshlayout.setLoadmoreFinished(false);//将会再次触发加载更多事件
                getMvpPresenter().getOrderList(page, String.valueOf(ORDER_TYPE));
            } else {
                refreshlayout.finishLoadmore();
                mRefreshlayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
            }
        });
    }

    @Override
    public void getOrderList(OrderListResponse bean) {
        if (mErrorLayout.getVisibility() == View.VISIBLE) {
            mErrorLayout.setVisibility(View.GONE);
            mRefreshlayout.setVisibility(View.VISIBLE);
        }
        mRefreshlayout.finishRefresh();
        mRefreshlayout.finishLoadmore();
        if (bean.data != null) {
            if (page == 1) mOrderList.clear();
            page += 1;
            totalPage = bean.data.totalPage;
            if (bean.data.list != null) {
                mOrderList.addAll(bean.data.list);
                for (int i = 0; i < mOrderList.size(); i++) {
                    mRecyclerView.expandGroup(i);
                }
                adapter.notifyDataSetChanged();
            }
            mRefreshlayout.setVisibility(mOrderList.size() == 0 ? View.GONE : View.VISIBLE);
            mEmptyLayout.setVisibility(mOrderList.size() == 0 ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public void cancelOrder(BaseProtocal baseProtocal) {
        toast(baseProtocal.msg);
        reloadData();
    }

    private void reloadData() {
        totalPage = 0;
        page = 1;
        getMvpPresenter().getOrderList(page, String.valueOf(ORDER_TYPE));

    }

    @Override
    public void confirmOrder(BaseProtocal baseProtocal) {
        toast(baseProtocal.msg);
        reloadData();
    }

    @Override
    public void onRequestFailure(int requestType, int errorCode, String msg) {
        if (mRefreshlayout.isRefreshing()) {
            mRefreshlayout.finishRefresh();
        } else
            mRefreshlayout.finishLoadmore();
        if (requestType == Constants.NEED_CHANGE_UI_TYPE) {
            mRefreshlayout.setVisibility(View.GONE);
            mErrorLayout.setVisibility(View.VISIBLE);
        }
        ToastUtil.showToast(getActivity(), msg);
    }

    @Override
    public void onLoading(String text) {
        if (!mRefreshlayout.isRefreshing() || !mRefreshlayout.isLoading()) {
            LoadingUtils.createLoadingDialog(getActivity(), text, true);
        }
    }

    /**
     * 取消订单dialog
     */
    private void showCancelOrderDialog(final String payment_id) {
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("订单取消确认")
                .setMessage("取消了可能会被抢光哟~")
                .setPositiveButton("仍然取消", (dialog1, which) -> getMvpPresenter().cancelOrder(payment_id))
                .setNegativeButton("我再想想", null)
                .show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(context.getResources().getColor(R.color.color_ff4138));
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.gray_6));
    }

    /**
     * 确认收货dialog
     */
    private void showSureConfirmDialog(final String payment_id) {
        AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setTitle("订单确认收货")
                .setMessage("确认收到货物了再点哦~")
                .setPositiveButton("确认收货", (dialog1, which) -> getMvpPresenter().confirmOrder(payment_id))
                .setNegativeButton("取消", null)
                .show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(context.getResources().getColor(R.color.color_ff4138));
        dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(context.getResources().getColor(R.color.gray_6));
    }
}

